<template>
  <view class="warehouse-container">
    <!-- A. 页面头部 -->
    <view class="page-header">
      <text class="page-title">{{ pageTitle }}</text>
    </view>

    <!-- B. 主信息区 -->
    <view class="info-section" v-if="showCustomFilters">
      <view class="section-header">
        <text class="section-title">查询信息</text>
      </view>
      <view class="info-form">
        <!-- 自定义筛选条件插槽 -->
        <slot
          name="custom-filters"
          :formData="formData"
          :handleCustomFilterChange="handleCustomFilterChange"
        ></slot>
      </view>
    </view>

    <!-- C. 时间筛选按钮组 -->
    <view class="search-section" v-if="showTimeFilter">
      <view class="section-header">
        <text class="section-title">日期条件</text>
        <view class="time-filter-buttons">
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'yesterday' }"
            @tap="handleTimeChange('yesterday')"
          >
            昨
          </button>
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'today' }"
            @tap="handleTimeChange('today')"
          >
            今
          </button>
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'tomorrow' }"
            @tap="handleTimeChange('tomorrow')"
          >
            明
          </button>
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'week' }"
            @tap="handleTimeChange('week')"
          >
            7天
          </button>
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'month' }"
            @tap="handleTimeChange('month')"
          >
            30天
          </button>
        </view>
      </view>
    </view>

    <!-- D. 主表数据 -->
    <view class="info-section" v-if="showMainTable">
      <view class="section-header">
        <text class="section-title">查询结果</text>
        <view class="statistics-info" v-if="showMainTableStats">
          <text class="stat-item">查询条目: {{ mainTableData.length }} 条</text>
        </view>
      </view>
      <view class="table-scroll-container">
        <scroll-view
          class="table-scroll-wrapper"
          scroll-x
          scroll-with-animation
        >
          <view class="table-content">
            <view class="table-row header">
              <text class="header-cell select-col" v-if="showRowSelection"
                >选择</text
              >
              <text
                v-for="column in mainTableColumns"
                :key="column.key"
                class="header-cell"
                >{{ column.title }}</text
              >
            </view>
            <view
              v-for="(item, index) in mainTableData"
              :key="index"
              class="table-row"
              :class="{
                selected:
                  selectedMainRow &&
                  selectedMainRow[mainTableKey] === item[mainTableKey],
              }"
              @click="selectMainRow(item)"
            >
              <view class="table-cell select-col" v-if="showRowSelection">
                <view class="custom-checkbox" @click.stop="selectMainRow(item)">
                  <view
                    class="checkbox-icon"
                    :class="{
                      'checkbox-checked':
                        selectedMainRow &&
                        selectedMainRow[mainTableKey] === item[mainTableKey],
                    }"
                  >
                    <text
                      v-if="
                        selectedMainRow &&
                        selectedMainRow[mainTableKey] === item[mainTableKey]
                      "
                      class="check-mark"
                      >✓</text
                    >
                  </view>
                </view>
              </view>
              <text
                v-for="column in mainTableColumns"
                :key="column.key"
                class="table-cell"
                >{{ formatCellValue(item, column) }}</text
              >
            </view>
          </view>
        </scroll-view>
        <view class="scroll-hint" :class="{ show: mainTableData.length > 0 }">
          <text class="hint-icon">↔</text>
          横向滑动查看更多
        </view>
      </view>
    </view>

    <!-- E. 明细表数据 -->
    <view
      class="material-table-section"
      v-if="showDetailTable && selectedMainRow"
    >
      <view class="section-header">
        <text class="section-title">参数输入</text>
        <view class="statistics-info" v-if="showDetailTableStats">
          <text class="stat-item"
            >合计: {{ totalWeight }} KG / {{ totalQuantity }} 件</text
          >
        </view>
      </view>
      <view class="table-scroll-container">
        <scroll-view
          class="table-scroll-wrapper"
          scroll-x
          scroll-with-animation
        >
          <view class="table-content">
            <view class="table-row header">
              <text
                v-for="column in detailTableColumns"
                :key="column.key"
                class="header-cell"
                >{{ column.title }}</text
              >
            </view>
            <view
              v-for="(item, index) in detailTableData"
              :key="index"
              class="table-row"
            >
              <text
                v-for="column in detailTableColumns"
                :key="column.key"
                class="table-cell"
                >{{ formatDetailCellValue(item, column) }}</text
              >
            </view>
          </view>
        </scroll-view>
        <view class="scroll-hint" :class="{ show: detailTableData.length > 0 }">
          <text class="hint-icon">↔</text>
          横向滑动查看更多
        </view>
      </view>
    </view>
  </view>
</template>

<script>
// 导入API方法
import { warehouseApi } from "@/api/warehouse/warehouse";
import { dateHelperApi } from "@/pages/smart/warehouse/utils/date-helper";

export default {
  name: "QueryTemplate",
  props: {
    // 页面标题
    pageTitle: {
      type: String,
      default: "查询页面",
    },
    // 主表标题
    mainTableTitle: {
      type: String,
      default: "主表数据",
    },
    // 明细表标题
    detailTableTitle: {
      type: String,
      default: "明细表数据",
    },
    // 主表列配置
    mainTableColumns: {
      type: Array,
      default: () => [],
    },
    // 明细表列配置
    detailTableColumns: {
      type: Array,
      default: () => [],
    },
    // 查询API方法
    queryApi: {
      type: Function,
      required: true,
    },
    // 明细查询API方法
    detailApi: {
      type: Function,
      default: null,
    },
    // 主表数据键名
    mainTableKey: {
      type: String,
      default: "id",
    },
    // 显示配置
    showCustomFilters: {
      type: Boolean,
      default: false,
    },
    showTimeFilter: {
      type: Boolean,
      default: true,
    },
    showMainTable: {
      type: Boolean,
      default: true,
    },
    showDetailTable: {
      type: Boolean,
      default: true,
    },
    showRowSelection: {
      type: Boolean,
      default: true,
    },
    showMainTableStats: {
      type: Boolean,
      default: true,
    },
    showDetailTableStats: {
      type: Boolean,
      default: true,
    },
    // 自定义查询参数
    customParams: {
      type: Object,
      default: () => ({}),
    },
    // 自定义表单数据
    customFormData: {
      type: Object,
      default: () => ({}),
    },
    // 数据格式化函数
    dataFormatter: {
      type: Function,
      default: null,
    },
    // 明细数据格式化函数
    detailDataFormatter: {
      type: Function,
      default: null,
    },
  },
  data() {
    return {
      // 表单数据
      formData: {
        // 支持自定义字段
        ...this.customFormData,
      },

      // 时间筛选器
      timeFilter: "today",
      // 时间范围
      timeRange: {
        startTime: "",
        endTime: "",
      },

      // 主表数据
      mainTableData: [],
      // 明细表数据
      detailTableData: [],
      // 选中的主表行
      selectedMainRow: null,

      // 加载状态
      loading: false,
    };
  },
  computed: {
    // 日期工具命名空间（供模板使用）
    dateHelperApi() {
      return dateHelperApi;
    },
    // 所有明细行总重量
    totalWeight() {
      return this.detailTableData
        .reduce((total, item) => {
          return total + (parseFloat(item.prodCount) || 0);
        }, 0)
        .toFixed(3);
    },
    // 所有明细行总数量
    totalQuantity() {
      return this.detailTableData.reduce((total, item) => {
        return total + (parseInt(item.transCount) || 0);
      }, 0);
    },
  },
  onLoad() {
    // 页面加载时初始化时间范围并加载数据
    this.handleTimeChange("today");
    this.$nextTick(() => {
      this.loadMainTableData();
    });
  },

  methods: {
    /* 处理自定义筛选条件变化 */
    handleCustomFilterChange(field, value) {
      this.formData[field] = value;
      this.loadMainTableData();
    },

    /* 时间选择处理 */
    handleTimeChange(timeFilter) {
      // 更新时间筛选器
      this.timeFilter = timeFilter;

      // 使用通用的updateDateRange函数处理所有时间类型
      const result = dateHelperApi.updateDateRange(timeFilter, {
        callback: ({ startDate, endDate }) => {
          // 更新时间范围
          this.timeRange = {
            startTime: startDate,
            endTime: endDate,
          };
        },
      });

      // 重新加载数据
      this.$nextTick(() => {
        this.loadMainTableData();
      });
    },

    /* 加载主表数据 */
    async loadMainTableData() {
      if (this.loading) return;
      this.loading = true;
      //清空主表数据
      this.mainTableData = [];
      try {
        const params = {
          ...this.formData,
          ...this.customParams,
          pageNo: 1,
          pageSize: 100,
        };

        // 添加时间范围参数
        if (
          this.showTimeFilter &&
          this.timeRange.startTime &&
          this.timeRange.endTime
        ) {
          params.createTime = [
            this.timeRange.startTime,
            this.timeRange.endTime,
          ];
        }

        console.log("查询主表参数:", params);
        const response = await this.queryApi(params);
        console.log("主表数据响应:", response);

        if (response.code === 0) {
          let data =
            response.data.list || response.data.records || response.data || [];

          // 如果提供了数据格式化函数，使用它
          if (this.dataFormatter && typeof this.dataFormatter === "function") {
            data = this.dataFormatter(data);
          }

          this.mainTableData = data;
          // 清空明细数据和选择
          this.detailTableData = [];
          this.selectedMainRow = null;
        } else {
          uni.showToast({
            title: response.message || "加载主表数据失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("加载主表数据失败:", error);
        uni.showToast({
          title: "请求失败: " + error.message,
          icon: "none",
        });
      }

      this.loading = false;
    },

    /* 选择主表行 */
    async selectMainRow(row) {
      console.log("选择主表行:", row);
      if (
        this.selectedMainRow &&
        this.selectedMainRow[this.mainTableKey] === row[this.mainTableKey]
      ) {
        console.log("点击已选中的行，取消选择:", row);
        // 如果点击已选中的行，则取消选择
        this.selectedMainRow = null;
        this.detailTableData = [];
        return;
      }

      console.log("选择新行，ID:", row[this.mainTableKey]);
      this.selectedMainRow = row;

      // 如果有明细查询API，加载对应的明细数据
      if (this.detailApi && typeof this.detailApi === "function") {
        console.log("开始加载明细数据...");
        await this.loadDetailTableData(row[this.mainTableKey]);
        console.log("明细数据加载完成，数据量:", this.detailTableData.length);
      }
    },

    /* 加载明细表数据 */
    async loadDetailTableData(mainId) {
      if (this.loading || !this.detailApi) return;
      this.loading = true;

      try {
        console.log("开始加载明细表数据，主表ID:", mainId);
        const response = await this.detailApi(mainId);
        console.log("明细表数据响应:", response);

        if (response.code === 0) {
          // 检查数据结构，可能是 response.data 直接是数组，或者 response.data.list 是数组
          let detailData = [];
          if (Array.isArray(response.data)) {
            detailData = response.data;
          } else if (response.data && Array.isArray(response.data.list)) {
            detailData = response.data.list;
          } else if (response.data && response.data.records) {
            detailData = response.data.records;
          } else if (response.data) {
            // 如果data是对象，尝试从中提取数组
            const keys = Object.keys(response.data);
            console.log("响应data的键:", keys);
            for (let key of keys) {
              if (Array.isArray(response.data[key])) {
                detailData = response.data[key];
                console.log("找到数组数据在键:", key);
                break;
              }
            }
            if (detailData.length === 0) {
              console.warn("未找到明细数据数组，尝试将整个data作为单个记录");
              detailData = [response.data]; // 作为单个记录
            }
          } else {
            detailData = [];
            console.warn("未找到明细数据，数据结构:", response.data);
          }

          // 如果提供了明细数据格式化函数，使用它
          if (
            this.detailDataFormatter &&
            typeof this.detailDataFormatter === "function"
          ) {
            detailData = this.detailDataFormatter(detailData);
          }

          // 确保所有项目都有必要的字段
          this.detailTableData = detailData.map((item) => ({
            ...item,
            transCount: item.transCount || item.quantity || 0,
            prodCount: item.prodCount || item.weight || item.quantity || 0,
            prodPrice: item.prodPrice || item.price || 0,
            materialCode: item.materialCode || item.matCode || "",
            materialName: item.materialName || item.matName || "",
            specification: item.specification || item.spec || "",
          }));

          console.log("处理后的明细表数据:", this.detailTableData);

          // 如果没有数据，显示提示
          if (this.detailTableData.length === 0) {
            uni.showToast({
              title: "该单据暂无明细数据",
              icon: "none",
            });
          }
        } else {
          uni.showToast({
            title: response.message || "加载明细数据失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("加载明细数据失败:", error);
        uni.showToast({
          title: "请求失败: " + error.message,
          icon: "none",
        });
      }

      this.loading = false;
    },

    /* 格式化单元格值 */
    formatCellValue(item, column) {
      const value = item[column.dataIndex];

      // 如果提供了自定义格式化函数
      if (column.formatter && typeof column.formatter === "function") {
        return column.formatter(value, item);
      }

      // 日期格式化
      if (column.dataType === "date" && value) {
        return dateHelperApi.formatDate(value);
      }

      // 数字格式化
      if (column.dataType === "number" && typeof value === "number") {
        if (column.precision !== undefined) {
          return value.toFixed(column.precision);
        }
        return value;
      }

      // 默认值处理
      return value || column.defaultValue || "-";
    },

    /* 格式化明细单元格值 */
    formatDetailCellValue(item, column) {
      const value = item[column.dataIndex];

      // 如果提供了自定义格式化函数
      if (column.formatter && typeof column.formatter === "function") {
        return column.formatter(value, item);
      }

      // 日期格式化
      if (column.dataType === "date" && value) {
        return dateHelperApi.formatDate(value);
      }

      // 数字格式化
      if (column.dataType === "number" && typeof value === "number") {
        if (column.precision !== undefined) {
          return value.toFixed(column.precision);
        }
        return value;
      }

      // 默认值处理
      return value || column.defaultValue || "-";
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/pages/smart/scss/create.scss";
</style>
